<template>
  <div class="scrollable-container" @scroll="handleScroll">
    <div class="main-layout-header">
      <!--登录/注册入口-->
      <router-link to="/Login" v-if="loginStore.loginInfo === 0">登录</router-link>
      <!--个人中心入口-->
      <el-dropdown v-if = "loginStore.loginInfo == 1" class = "peopleInfo">
        <div>
          <el-avatar :src="customerInfoStore.customerInfo.image? customerInfoStore.customerInfo.image : avatar" />
          <span class = "el-dropdown-link">
            您好，{{ customerInfoStore.customerInfo.name }}
            <el-icon class="el-icon--right">
              <arr-down />
            </el-icon>
          </span>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <p @click="redirectToCustomerPlace">个人中心</p>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-dropdown v-if = "loginStore.loginInfo == 2" class = "peopleInfo">
        <div>
          <el-avatar :src="businessInfoStore.businessInfo.image? businessInfoStore.businessInfo.image : avatar" />
          <span class = "el-dropdown-link">
            您好，{{ businessInfoStore.businessInfo.name }}
            <el-icon class="el-icon--right">
              <arr-down />
            </el-icon>
          </span>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <p @click="redirectToBusinessPlace">个人中心</p>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <!-- <el-input
        v-model="input1"
        style="width: 400px"
        size="large"
        placeholder="请输入您要查找的商品名"
      /> -->
    </div>
    <div class="item-grid">
      <div
        v-for="(item) in displayedItems"
        :key="item.id"
        class="item"
      >
        <div class="item-container" @click="redirectToItem(item.id)">
          <div class="item-image">
            <img :src="item.image" alt="Item Image" class="image"/>
          </div>
          <div class="price">￥{{ item.price }}</div>
          <div class="name">{{ item.title }}</div>
          <div class="business">商家:{{ item.business }}</div>
          <div class="province">省份: {{ item.province }}</div>
          <div class="area">地区: {{ item.area }}</div>
          <div class="salesNum">销量: {{ item.salesNum }}</div>
        </div>
      </div>
      <div v-if="loading && !isEnd" class="loading">加载中...</div>
    </div>
    <div v-if="isEnd" class="bottom">已经触及底部，没有更多商品了......</div>
  </div>
</template>

<script>

import avatar from '@/assets/default.png'  //默认头像
import { addBrowsingHistoryService, getGoodsDataService, getGoodsDetailDataService } from '@/api/goods'
import { useCustomerInfoStore } from '@/store/customerInfo'
import { useBusinessInfoStore } from '@/store/businessInfo'
import { useLoginStore } from '@/store/login'
import { customerInfoService } from '@/api/Customer'
import { businessInfoService } from '@/api/Business'
import { useTokenStore } from '@/store/token'
import { ElMessage } from 'element-plus'

export default {

  setup() {
    const customerInfoStore = useCustomerInfoStore();  //存储顾客信息
    const businessInfoStore = useBusinessInfoStore();  //存储商家信息
    const token = useTokenStore();  //存放令牌
    const loginStore = useLoginStore();  //存放登录信息，1——当前登录的是顾客，0——未登录，2——登录的是商家

    const checkToken = async () => {
      //检查有没有token，有——曾经登陆过，没有——未登录
      if(token.token) {
        /*
          检查loginStore存放的是不是1，是——去后端获取顾客信息，否——去后端获取商家信息，如果获取不到，
          证明token过期，提示要重新登录
        */
        if(loginStore.loginInfo.valueOf === 1) {
          await customerInfoService();
        }else {
          await businessInfoService();
        }
      }
    }
    checkToken();
    return { customerInfoStore, businessInfoStore, token, loginStore }
  },

  data() {
    return {
      displayedItems: [], //控制现在加载出的商品
      loading: false, //判断是否在加载中
      isEnd: false, //判断是否到达底部（即数据库所有数据都取出来了）
      itemsPageNum: 1,  //当前读到第几页
      itemsPerLoad: 16, //每次加载的商品数量
      total: 0,   //总页数
    };
  },

  //钩子，当满足特定条件就运行里面内容
  mounted() {
    this.loadMoreItems(); 
  },

  methods: {

    //loadMoreItems:
    async loadMoreItems() {
      //判断是否在加载中，是则返回，否则则代表可以导入
      if (this.loading) return;
      this.loading = true;
      //存储分页信息
      const params = {
        pageNum: this.itemsPageNum,
        pageSize: this.itemsPerLoad,
      };
      //获取商品数据
      let item = await getGoodsDataService(params);
      this.displayedItems.push(...item.data.items);
      this.total=item.data.total;
      //判断是否取完后端数据
      if(this.total<(this.itemsPageNum)*(this.itemsPerLoad))
      {
        this.isEnd=true;
      }
      else {
        this.loading=false;
        this.itemsPageNum++;
      }
    },

    //判断是否到达底部
    handleScroll(event) {
      const { scrollTop, scrollHeight, clientHeight } = event.target;
      if (scrollTop + clientHeight >= scrollHeight - 5) {
        this.loadMoreItems();
      }
    },

    //去商品详细界面信息
    async redirectToItem(id) {
      if(this.loginStore.loginInfo == 2)
      {
        ElMessage.error('当前登录身份为商家，无法查看商品详情');
        return ;
      }
      if(this.loginStore.loginInfo == 0)
      {
        ElMessage.error('当前尚未登录，无法查看商品详情');
        return ;
      }
      const url = this.$router.resolve({name: 'goodsDetails', params: {id}, query: {id}}).href;
      //获取当前时间，以便存储到浏览记录内
      const now = new Date();
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 24小时制
        timeZone: 'Asia/Shanghai' // 设置时区为上海，即中国标准时间
      };
      const result = await getGoodsDetailDataService(id);
      const item = result.data;
      const localTime = now.toLocaleString('sv-SE', options).replace(',', '');
      const data = {
        "goodsName": item.title,
        "customerName": "1",
        "businessName": item.business,
        "browsingTime": localTime,
        "image": item.image
      }
      //存储浏览记录
      await addBrowsingHistoryService(data);
      window.open(url, '_blank');
    },

    //前往顾客个人中心
    redirectToCustomerPlace() {
      const url = this.$router.resolve({name: 'customerPlace'}).href;
      window.open(url, '_blank');
    },

    //前往商家个人中心
    redirectToBusinessPlace() {
      const url = this.$router.resolve({name: 'businessPlace'}).href;
      window.open(url, '_blank');
    }
  },
};
</script>

<style scoped>
  /* 控制整个界面的样式 */
  .scrollable-container {
    height: 100%;
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    overflow-y: auto;
  }

  /* 控制头部样式 */
  .main-layout-header {
    line-height: 60px;
    text-align: center;
    position: relative;
    background-color: #B3C0D1;
    color: #333;
  }

  /* 控制所有商品所处位置的样式 */
  .item-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-content: center;
    padding-left: 15%;
    padding-right: 15%;
  }

  /* 控制每个商品的样式 */
  .item-container {
    position: relative; /* 定位边框 */
    cursor: pointer; /* 鼠标悬停时显示手型 */
    border: 2px solid transparent; /* 初始边框为透明 */
    transition: border-color 0.3s; /* 添加过渡效果 */
  }

  .item-container:hover {
    border-color: blue; /* 悬停时边框变为蓝色 */
  }

  .item {
    width: calc(25% - 10px); /* 每行 4 个图片，减去间距 */
    margin: 5px; /* 间距 */
    cursor: pointer; /* 添加手指光标以表示可点击 */
  }

  .item-image {
    width: 100%;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /* 控制图片,商品信息格式 */
  .image {
    max-width: 100%;
    max-height: 100%;
    width: auto;
    height: auto; /* 自适应高度 */
  }

  .name, .business, .area, .province, .salesNum {
    color: #555;
    margin: 5px 0;
    font-size: 14px;
  }

  .price {
    cursor: pointer;
    color: blue;
    text-decoration: underline;
    display: flex;
    justify-content: center;
    align-content: center;
    text-align: center;
  }

  /* 控制加载中格式 */
  .loading {
    display: flex;
    justify-content: center;
    align-content: center;
    text-align: center;
    padding: 10px 0;
    height: 50px;
  }

  /* 控制底部样式 */
  .bottom {
    display: flex;
    justify-content: center;
    align-content: center;
    text-align: center;
    height: 50px;
  }
</style>